import {
	defineStore
} from "pinia";
import {
	MESSAGE_TYPE,
	MESSAGE_STATUS
} from "@/common/enums.js";
import useUserStore from "./userStore";
import useCompanyStore from "./companyStore";
import {
	MyURLSearchParams,
	uniqueArrayWithObjects
} from "@/utils";
import request from "@/common/request";

let cacheChats = [];
export default defineStore("chatStore", {
	state: () => {
		return {
			chats: [],
			/**
			 * 友商列表私聊会话
			 */
			businessPrivateChats: [],
			/**
			 * 工作号私聊会话
			 */
			workPrivateChats: [],
			/**
			 * 消息聊天列表
			 */
			privateChats: [],
			/**
			 * 友商聊天列表
			 */
			friendBusinessChats: [],
			/**
			 * 公司聊天列表
			 */
			companyChats: [],
			chatType: {
				PRIVATE: "PRIVATE",
				BUSINESS: "BUSINESS",
				GROUP: "GROUP",
				COMPANY: "COMPANY",
				WORKPRIVATE: 'WORKPRIVATE',
			},
			company: {},
			privateMsgMaxId: 0,
			groupMsgMaxId: 0,
			loadingPrivateMsg: false,
			loadingGroupMsg: false,
			addressInfo: {},
		};
	},
	actions: {
		initChats(chatsData) {
			cacheChats = [];
			this.chats = [];
			for (let chat of chatsData.chats) {
				// 暂存至缓冲区
				chat.stored = false;
				cacheChats.push(JSON.parse(JSON.stringify(chat)));
				// 加载期间显示只前15个会话做做样子,一切都为了加快初始化时间
				if (this.chats.length < 15) {
					this.chats.push(chat);
				}
			}
			this.privateMsgMaxId = chatsData.privateMsgMaxId || 0;
			this.groupMsgMaxId = chatsData.groupMsgMaxId || 0;
			// 防止图片一直处在加载中状态
			cacheChats.forEach((chat) => {
				chat.messages.forEach((msg) => {
					if (msg.loadStatus == "loading") {
						msg.loadStatus = "fail";
					}
				});
			});
		},
		setAddressInfo(addressInfo) {
			this.addressInfo = addressInfo;
		},
		/**
		 * @param {Object} type PRIVATE|GROUP
		 * @param {Object} targetId 目标用户id
		 * @param {Object} urlParams 路径参数
		 */
		openChatRedirect(type, targetId, urlParams = {}) {
			this.openChat({
				targetId: targetId,
				type: type,
			});
			// let chatIdx = this.findChatIdx(chat);
			const params = {
				...urlParams,
				id: targetId,
				type: type,
			};

			const queryString = new MyURLSearchParams(params).toString();
			uni.navigateTo({
				url: `/pageSubOne/chat/chat-box?${queryString}`,
			});
		},
		openChat(chatInfo) {
			/* const idx = this.findChatIdx({
				id: chatInfo.targetId,
				type: chatInfo.type,
			})
			let chat = this.chats[idx]
			this.moveTop(idx) */
			let chats = this.curChats;
			let chat = null;
			for (let idx in chats) {
				if (
					chats[idx].type == chatInfo.type &&
					chats[idx].targetId == chatInfo.targetId
				) {
					chat = chats[idx];
					// 放置头部
					this.moveTop(idx);
					break;
				}
			}
			// 创建会话
			if (chat == null) {
				let getInfo = null;
				if (chatInfo.type == this.chatType.PRIVATE) {
					getInfo = getApp().$vm.loadFriendInfo
				} else if (chatInfo.type == this.chatType.BUSINESS) {
					getInfo = getApp().$vm.loadFriendInfo
				} else {
					getInfo = getApp().$vm.loadGroupInfo
				}
				getInfo(chatInfo.targetId, (info) => {
					if (info) {
						chat = {
							...chatInfo,
							type: chatInfo.type,
							targetId: chatInfo.targetId,
							lastContent: "",
							lastSendTime: new Date().getTime(),
							unreadCount: 0,
							messages: [],
							originalData: info,
							atMe: false,
							atAll: false,
							stored: false,
							showName: info.nickName || info.showGroupName,
						};
						// 根据类型分别处理
						if (chatInfo.type === this.chatType.BUSINESS) {
							// 确保 businessPrivateChats 已初始化
							this.businessPrivateChats = this.businessPrivateChats || [];
							// 添加到友商聊天列表
							this.businessPrivateChats.unshift(chat);
						}
						chats.unshift(chat);
						// getApp().$vm.init();

					}
				})
			}
		},
		activeChat(idx) {
			let chats = this.curChats;
			if (idx >= 0) {
				chats[idx].unreadCount = 0;
			}
		},
		resetUnreadCount(chatInfo) {
			let chats = this.curChats;
			for (let idx in chats) {
				if (
					chats[idx].type == chatInfo.type &&
					chats[idx].targetId == chatInfo.targetId
				) {
					chats[idx].unreadCount = 0;
					chats[idx].atMe = false;
					chats[idx].atAll = false;
					chats[idx].stored = false;
					this.saveToStorage();
				}
			}
		},
		resetUnreadCountByIdx(idx) {
			this.chats[idx].unreadCount = 0;
			this.chats[idx].atMe = false;
			this.chats[idx].atAll = false;
			this.chats[idx].stored = false;
			this.saveToStorage();
		},
		// todo友商已读有点问题
		readedMessage(pos) {

			let chat = null;
			// 根据消息类型查找对应的聊天
			if (pos.type == 1) {
				chat = this.businessChatByFriend(pos.friendId);
			} else {
				chat = this.findChatByFriend(pos.friendId);
			}
			if (!chat) {
				this.openChat({
					targetId: pos.friendId,
					type: this.chatType.PRIVATE
				})
				chat = this.findChatByFriend(pos.friendId);
			}
			chat.messages.forEach((m) => {
				if (m.id && m.selfSend && m.status < MESSAGE_STATUS.RECALL) {
					// pos.maxId为空表示整个会话已读
					if (!pos.maxId || m.id <= pos.maxId) {
						m.status = MESSAGE_STATUS.READED;
						chat.stored = false;
					}
				}
			});
			if (!chat.stored) {
				this.saveToStorage();
			}
		},


		/**
		 * 根据聊天类型和目标ID删除聊天会话
		 * @param {string} type - 聊天类型 (PRIVATE|BUSINESS|GROUP)
		 * @param {string} targetId - 目标ID（用户ID或群组ID）
		 * @returns {Object} - 删除结果
		 */
		removeChatByTypeAndId(type, targetId) {
			// 参数验证
			if (!type || !targetId) {
				throw new Error('Invalid type or targetId');
			}

			let chats = this.curChats;

			// 查找并删除匹配的聊天
			for (let idx in chats) {
				if (chats[idx].type === type &&
					chats[idx].targetId === targetId) {
					this.removeChat(idx);
				}
			}

		},
		removeChat(idx) {

			let chats = this.curChats;
			chats[idx].delete = true;
			chats[idx].stored = false;

			this.saveToStorage();
		},
		removePrivateChat(userId) {

			let chats = this.curChats;
			for (let idx in chats) {
				if (chats[idx].type == "PRIVATE" && chats[idx].targetId == userId) {
					this.removeChat(idx);
				}
			}
		},
		/**
		 * 删除已经被解散的群聊
		 */
		removeDeleteGroup() {
			const dissolveMap = {};
			for (var i = 0; i < this.curChats.length; i++) {
				if (this.curChats[i].originalData.dissolve) {
					dissolveMap[i] = this.curChats[i];
					this.removeChat(i);
				}
			}
		},
		removeGroupChat(groupId) {
			let chats = this.curChats;
			for (let idx in chats) {
				if (chats[idx].type == "GROUP" && chats[idx].targetId == groupId) {
					this.removeChat(idx);
				}
			}
		},
		/**根据taigetId置顶
		 * @param {Object} targetId
		 */
		moveTopByTargetId(targetId) {
			if (this.isLoading()) {
				return;
			}
			let chats = this.curChats;
			let idx = chats.findIndex((e) => e.targetId == targetId);
			let chat = chats[idx];
			const value = !(
				chat.originalData &&
				chat.originalData.onTop &&
				chat.originalData.onTop
			);
			request({
				url: chat.type == "GROUP" ? "/group/modify" : "/friend/update",
				method: "PUT",
				data: {
					id: chat.targetId,
					onTop: value,
				},
			}).finally(() => {
				chat.originalData.onTop = value;
				// 如果是置顶就挪到最顶上
				if (value) {
					chats.splice(idx, 1);
					chats.unshift(chat);
				} else {
					// 如果是取消置顶就挪到最后一个置顶的后一位
					let lastOnTopIndex = chats.reduce((acc, c, i) => {
						if (c.originalData && c.originalData.onTop) {
							acc = i;
						}
						return acc;
					}, -1);
					if (lastOnTopIndex !== -1) {
						chats.splice(idx, 1);
						chats.splice(lastOnTopIndex, 0, chat);
					} else {
						// 如果没有其他置顶项，则挪到最后
						chats.splice(idx, 1);
						chats.push(chat);
					}
				}
				this.saveToStorage();
				chat.lastSendTime = new Date().getTime();
				chat.stored = false;
			});
			// }
		},
		moveTop(idx) {
			if (this.isLoading()) {
				return;
			}
			let chats = this.curChats;
			// if (idx > 0) {
			let chat = chats[idx];
			const value = !(chat &&
				chat.originalData &&
				chat.originalData.onTop &&
				chat.originalData.onTop
			);
			// 如果是置顶就挪到最顶上
			if (value) {
				chats.splice(idx, 1);
				chats.unshift(chat);
			} else {
				// 挪到最后一个置顶后一位
				let lastOnTopIndex = chats.reduce((acc, c, i) => {
					if (c.originalData && c.originalData.onTop) {
						acc = i;
					}
					return acc;
				}, -1);
				if (lastOnTopIndex !== -1) {
					chats.splice(idx, 1);
					chats.splice(lastOnTopIndex, 0, chat);
				} else {
					// 如果没有其他置顶项，则挪到最后
					chats.splice(idx, 1);
					chats.push(chat);
				}
			}
			this.saveToStorage();
			chat.lastSendTime = new Date().getTime();
			chat.stored = false;
			// }
		},
		updateOriginalDataByIdx(idx, originalData) {
		 let chats = this.curChats;
		
		  // 检查索引是否有效
		  if (idx < 0 || idx >= chats.length) {
		    console.error(`索引 ${idx} 越界，数组长度: ${chats.length}`);
		    return; // 或抛出错误 throw new Error("索引越界");
		  }
		
		  // 如果元素不存在，初始化空对象
		  if (!chats[idx]) {
		    chats[idx] = {}; // [!code ++]
		  }
		
		  // 安全赋值
		  chats[idx].companyId = originalData.companyId;
		  chats[idx].originalData = originalData;
		  this.saveToStorage();
		},
		insertMessage(msgInfo) {
			// 添加日志
			// 确定消息类型
			let type = msgInfo.groupId ? "GROUP" : (msgInfo.sourceType === 1 ? "BUSINESS" : "PRIVATE");

			// 记录消息的最大id
			if (
				msgInfo.id &&
				type == "PRIVATE" &&
				msgInfo.id > this.privateMsgMaxId
			) {
				this.privateMsgMaxId = msgInfo.id;
			}
			if (msgInfo.id && type == "GROUP" && msgInfo.id > this.groupMsgMaxId) {
				this.groupMsgMaxId = msgInfo.id;
			}
			// 如果是已存在消息，则覆盖旧的消息数据
			// console.log(msgInfo);
			let chat = this.findChat(msgInfo);

			let message = this.findMessage(chat, msgInfo);
			if (message) {
				Object.assign(message, msgInfo);
				// 撤回消息需要显示
				if (msgInfo.type == MESSAGE_TYPE.RECALL) {
					chat.lastContent = msgInfo.content;
				}
				chat.stored = false;
				this.saveToStorage();
				return;
			}
			// 会话列表内容
			if (msgInfo.type == MESSAGE_TYPE.IMAGE) {
				chat.lastContent = "[图片]";
			} else if (msgInfo.type == MESSAGE_TYPE.FILE) {
				chat.lastContent = "[文件]";
			} else if (msgInfo.type == MESSAGE_TYPE.AUDIO) {
				chat.lastContent = "[语音]";
			} else if (msgInfo.type == MESSAGE_TYPE.ACT_RT_VOICE) {
				chat.lastContent = "[语音通话]";
			} else if (msgInfo.type == MESSAGE_TYPE.ACT_RT_VIDEO) {
				chat.lastContent = "[视频通话]";
			} else if (
				msgInfo.type == MESSAGE_TYPE.TEXT ||
				msgInfo.type == MESSAGE_TYPE.RECALL ||
				msgInfo.type == MESSAGE_TYPE.TIP_TEXT
			) {
				// console.log(chat);
				chat.lastContent = msgInfo.content;
			}
			const userStore = useUserStore();
			chat.lastSendTime = msgInfo.sendTime;
			chat.sendNickName =
				userStore.userInfo.id == msgInfo.sendId ? "我" : msgInfo.sendNickName;
			// 未读加1
			if (
				!msgInfo.selfSend &&
				msgInfo.status != MESSAGE_STATUS.READED &&
				msgInfo.type != MESSAGE_TYPE.TIP_TEXT
			) {
				chat.unreadCount++;
			}
			// 是否有人@我
			if (
				!msgInfo.selfSend &&
				chat.type == "GROUP" &&
				msgInfo.atUserIds &&
				msgInfo.status != MESSAGE_STATUS.READED
			) {
				let userId = userStore.userInfo.id;
				if (msgInfo.atUserIds.indexOf(userId) >= 0) {
					chat.atMe = true;
				}
				if (msgInfo.atUserIds.indexOf(-1) >= 0) {
					chat.atAll = true;
				}
			}
			// 间隔大于10分钟插入时间显示
			if (
				!chat.lastTimeTip ||
				chat.lastTimeTip < msgInfo.sendTime - 600 * 1000
			) {
				chat.messages.push({
					sendTime: msgInfo.sendTime,
					type: MESSAGE_TYPE.TIP_TIME,
				});
				chat.lastTimeTip = msgInfo.sendTime;
			}
			// 根据id顺序插入，防止消息乱序
			let insertPos = chat.messages.length;
			// 防止 图片、文件 在发送方 显示 在顶端  因为还没存库，id=0
			if (msgInfo.id && msgInfo.id > 0) {
				for (let idx in chat.messages) {
					if (chat.messages[idx].id && msgInfo.id < chat.messages[idx].id) {
						insertPos = idx;
						console.log(
							`消息出现乱序,位置:${chat.messages.length},修正至:${insertPos}`
						);
						break;
					}
				}
			}
			if (insertPos == chat.messages.length) {
				// 这种赋值效率最高
				chat.messages[insertPos] = msgInfo;
			} else {
				chat.messages.splice(insertPos, 0, msgInfo);
			}
			chat.stored = false;
			this.saveToStorage();
		},
		updateMessage(msgInfo) {
			// 获取对方id或群id
			let chat = this.findChat(msgInfo);
			let message = this.findMessage(chat, msgInfo);
			if (message) {
				// 属性拷贝
				Object.assign(message, msgInfo);
				chat.stored = false;
				this.saveToStorage();
			}
		},
		deleteMessage(msgInfo) {
			// 获取对方id或群id
			let chat = this.findChat(msgInfo);
			for (let idx in chat.messages) {
				// 已经发送成功的，根据id删除
				if (chat.messages[idx].id && chat.messages[idx].id == msgInfo.id) {
					chat.messages.splice(idx, 1);
					break;
				}
				// 正在发送中的消息可能没有id，根据发送时间删除
				if (
					msgInfo.selfSend &&
					chat.messages[idx].selfSend &&
					chat.messages[idx].sendTime == msgInfo.sendTime
				) {
					chat.messages.splice(idx, 1);
					break;
				}
			}
			chat.stored = false;
			this.saveToStorage();
		},
		updateChatFromFriend(friend) {
			let chat = this.findChatByFriend(friend.id);
			if (
				chat &&
				(chat.headImage != friend.headImage || chat.showName != friend.nickName)
			) {
				// 更新会话中的群名和头像
				chat.headImage = friend.headImage;
				chat.showName = friend.nickName;
				chat.stored = false;
				this.saveToStorage();
			}
		},
		updateChatFromGroup(group) {
			let chat = this.findChatByGroup(group.id);
			if (
				chat &&
				(chat.headImage != group.headImage ||
					chat.showName != group.showGroupName)
			) {
				// 更新会话中的群名称和头像
				chat.headImage = group.headImage;
				chat.showName = group.showGroupName;
				chat.stored = false;
				this.saveToStorage();
			}
		},
		setLoadingPrivateMsg(loading) {
			this.loadingPrivateMsg = loading;
			if (!this.isLoading()) {
				this.refreshChats();
			}
		},
		setLoadingGroupMsg(loading) {
			this.loadingGroupMsg = loading;
			if (!this.isLoading()) {
				this.refreshChats();
			}
		},
		refreshChats() {
			if (!cacheChats) {
				return;
			}
			// 排序
			cacheChats.sort((chat1, chat2) => {
				return chat2.lastSendTime - chat1.lastSendTime;
			});
			// 将消息一次性装载回来
			this.chats = cacheChats;
			// 清空缓存
			cacheChats = null;
			this.saveToStorage();
		},
		saveToStorage(state) {
			// 对charts去重
			/* this.chats = uniqueArrayWithObjects(this.chats, "targetId");
			newChats.forEach(value => {
				// 使用 filter 方法找到匹配的聊天记录，并合并消息
				const matchingChats = this.chats.filter(chat => value.targetId === chat.targetId);
				// 合并所有匹配聊天的消息
				const allMessages = matchingChats.flatMap(chat => chat.messages);
				// 去重并赋值给 value.messages
				value.messages = uniqueArrayWithObjects(allMessages, "id");
			}); */
			this.chats = this.chats.sort((a, b) => {
				// 先按 onTop 排序，置顶的在前
				if (a.originalData.onTop && !b.originalData.onTop) return -1;
				if (!a.originalData.onTop && b.originalData.onTop) return 1;
				// 如果 onTop 相同，则按 lastSendTime 排序，最新的在前
				return b.lastSendTime - a.lastSendTime;
			});
			// 加载中不保存，防止卡顿
			if (this.isLoading()) {
				return;
			}
			const userStore = useUserStore();
			let userId = userStore.userInfo.id;
			let key = "chats-app-" + userId;
			let chatKeys = [];
			// 按会话为单位存储，只存储有改动的会话
			this.chats.forEach((chat) => {
				let chatKey = `${key}-${chat.type}-${chat.targetId}`;
				if (!chat.stored) {
					if (chat.delete) {
						uni.removeStorageSync(chatKey);
					} else {
						uni.setStorageSync(chatKey, chat);
					}
					chat.stored = true;
				}
				if (!chat.delete) {
					chatKeys.push(chatKey);
				}
			});
			// 会话核心信息
			let chatsData = {
				privateMsgMaxId: this.privateMsgMaxId,
				groupMsgMaxId: this.groupMsgMaxId,
				chatKeys: chatKeys,
			};
			uni.setStorageSync(key, chatsData);
			// 清理已删除的会话
			this.chats = this.chats.filter((chat) => !chat.delete);

			// 重置各种聊天消息
			this.resetFriendBusinessChats();
			this.resetPrivateChats();
			// 重置公司聊天列表
			const companyStore = useCompanyStore();
			companyStore.companyList.forEach((e) => {
				this.resetCompanyChats(e.id);
			});
		},
		removeAll() {
			
			this.clear();
			// 先删除后插入
			let userStore = useUserStore();
			let userId = userStore.userInfo.id;
			const location = uni.getStorageSync("location");
			const password = uni.getStorageSync("password");
			const userName = uni.getStorageSync("userName");
			const behavior = uni.getStorageSync("behavior");
			// 删除
			uni.clearStorageSync();
			if (location) {
				uni.setStorageSync("location", location);
			}
			if (password) {
				uni.setStorageSync("password", password);
			}
			if (userName) {
				uni.setStorageSync("userName", userName);
			}
			if (behavior) {
				uni.setStorageSync("behavior", behavior);
			}
		},
		clear(state) {
			cacheChats = [];
			this.chats = [];
			this.privateMsgMaxId = 0;
			this.groupMsgMaxId = 0;
			this.loadingPrivateMsg = false;
			this.loadingGroupMsg = false;
		},
		loadChat(context) {
			return new Promise((resolve, reject) => {
				let userStore = useUserStore();
				let userId = userStore.userInfo.id;
				let chatsData = uni.getStorageSync("chats-app-" + userId);
				if (chatsData) {
					if (chatsData.chatKeys) {
						let time = new Date().getTime();
						chatsData.chats = [];
						chatsData.chatKeys.forEach((key) => {
							let chat = uni.getStorageSync(key);
							if (chat) {
								chatsData.chats.push(chat);
							}
						});
					}
					this.initChats(chatsData);
				}
				resolve();
			});
		},
		/**
		 * 好友群和官方群聊天列表
		 */
		resetPrivateChats() {
			// 私聊或者是好友群或者是官方群
			this.privateChats = JSON.parse(JSON.stringify(this.chats)).filter(
				(chat) => {
					if (chat.type == this.chatType.PRIVATE) {
						const messages = []
						chat.lastContent = ""
						chat.sendNickName = ""
						for (var i = 0; i < chat.messages.length; i++) {
							if (chat.messages.length === 0) {
								continue
							}
							// 私聊移除友商sourceType=1的聊天记录
							if (chat.messages[i].sourceType && (chat.messages[i].sourceType === 1 || chat
									.messages[i].sourceType === 2)) {
								// 如果上一条是时间，就得删除友商消息的时间
								if (messages.length > 0 && messages[messages.length - 1].type === 20) {
									messages.pop()
								}
							} else {
								// 会话列表内容
								if (chat.messages[i].type == MESSAGE_TYPE.IMAGE) {
									chat.lastContent = "[图片]";
								} else if (chat.messages[i].type == MESSAGE_TYPE.FILE) {
									chat.lastContent = "[文件]";
								} else if (chat.messages[i].type == MESSAGE_TYPE.AUDIO) {
									chat.lastContent = "[语音]";
								} else if (chat.messages[i].type == MESSAGE_TYPE.ACT_RT_VOICE) {
									chat.lastContent = "[语音通话]";
								} else if (chat.messages[i].type == MESSAGE_TYPE.ACT_RT_VIDEO) {
									chat.lastContent = "[视频通话]";
								} else if (
									chat.messages[i].type == MESSAGE_TYPE.TEXT ||
									chat.messages[i].type == MESSAGE_TYPE.RECALL ||
									chat.messages[i].type == MESSAGE_TYPE.TIP_TEXT
								) {
									chat.lastContent = chat.messages[i].content;
								}

								const userStore = useUserStore();
								chat.lastContent = chat.messages[i].content
								chat.sendNickName = chat.messages[i].nickName
								chat.lastSendTime = chat.messages[i].sendTime;
								chat.sendNickName = userStore.userInfo.id == chat.messages[i].sendId ? "我" :
									chat.messages[i].sendNickName;
								messages.push(chat.messages[i])
							}
						}
						chat.messages = messages
						return chat
					} else if (chat.type == this.chatType.GROUP && [0, 2].includes(chat.originalData
							.groupType) && !chat.originalData.dissolve) {
						return chat
					}
				}
			);



			// 友商私聊
			this.businessPrivateChats = JSON.parse(JSON.stringify(this.chats)).filter(
				(chat) => {
					if (chat.type == this.chatType.BUSINESS) {
						const messages = []
						chat.lastContent = ""
						chat.sendNickName = ""
						for (var i = 0; i < chat.messages.length; i++) {
							if (chat.messages.length === 0) {
								continue
							}
							if (chat.messages[i].sourceType && chat.messages[i].sourceType === 1) {
								// 如果上一条是时间，先添加时间在前面再插入消息
								if (i > 0 && chat.messages[i - 1].type === 20) {
									messages.push(chat.messages[i - 1])
								}

								// 会话列表内容
								if (chat.messages[i].type == MESSAGE_TYPE.IMAGE) {
									chat.lastContent = "[图片]";
								} else if (chat.messages[i].type == MESSAGE_TYPE.FILE) {
									chat.lastContent = "[文件]";
								} else if (chat.messages[i].type == MESSAGE_TYPE.AUDIO) {
									chat.lastContent = "[语音]";
								} else if (chat.messages[i].type == MESSAGE_TYPE.ACT_RT_VOICE) {
									chat.lastContent = "[语音通话]";
								} else if (chat.messages[i].type == MESSAGE_TYPE.ACT_RT_VIDEO) {
									chat.lastContent = "[视频通话]";
								} else if (
									chat.messages[i].type == MESSAGE_TYPE.TEXT ||
									chat.messages[i].type == MESSAGE_TYPE.RECALL ||
									chat.messages[i].type == MESSAGE_TYPE.TIP_TEXT
								) {
									chat.lastContent = chat.messages[i].content;
								}



								const userStore = useUserStore();
								// chat.lastContent = chat.messages[i].content
								chat.sendNickName = chat.messages[i].nickName
								chat.lastSendTime = chat.messages[i].sendTime;
								chat.sendNickName = userStore.userInfo.id == chat.messages[i].sendId ? "我" :
									chat.messages[i].sendNickName;
								messages.push(chat.messages[i])
							}
						}
						chat.messages = messages
						return chat
					}
				}
			);

			// 工作私聊
			this.workPrivateChats = JSON.parse(JSON.stringify(this.chats)).filter((chat) => {
				// 只处理私聊类型
				if (chat.type == this.chatType.PRIVATE) {
					const messages = []

					// 遍历消息
					for (var i = 0; i < chat.messages.length; i++) {
						// 只保留工作消息(sourceType === 2)
						if (chat.messages[i].sourceType && chat.messages[i].sourceType === 2) {
							if (chat.messages.length === 0) {
								continue
							}
							// 保留时间消息
							if (i > 0 && chat.messages[i - 1].type === 20) {
								messages.push(chat.messages[i - 1])
							}

							// 更新会话状态
							const userStore = useUserStore();
							chat.lastContent = chat.messages[i].content
							chat.sendNickName = chat.messages[i].nickName
							chat.lastSendTime = chat.messages[i].sendTime;
							chat.sendNickName = userStore.userInfo.id == chat.messages[i].sendId ?
								"我" : chat.messages[i].sendNickName;

							// 保存工作消息
							messages.push(chat.messages[i])
						}
					}
					// 更新消息列表
					chat.messages = messages
					return chat
				}
			});
		},
		/**
		 * 友商群聊天列表
		 */
		resetFriendBusinessChats() {
			const companyStore = useCompanyStore();
			const companyIds = companyStore.companyList.map((e) => e.id);
			const list = []
			// 深拷贝当前聊天列表
			const chats = JSON.parse(JSON.stringify(this.chats))
		
			for (var i = 0; i < chats.length; i++) {
				const chat = chats[i]
				// 群聊，类型是1友商群 群类型3是体验官方群
				if (chat.type == this.chatType.GROUP && (chat.originalData.groupType == 1 || 
					chat.originalData.groupType == 3)&&
					
					//不是解散状态
					!chat.originalData.dissolve &&
					//不是自己公司的群
					(!chat.companyId || (chat.companyId && !companyIds.includes(chat.companyId)))
				) {
					list.push(chat)
				} else if (chat.type == this.chatType.BUSINESS) {
					// 友商私聊消息

					const bpchats = this.businessPrivateChats.filter(e => e.targetId == chat.targetId)

					if (bpchats && bpchats.length > 0) {
						list.push(bpchats[0])
					}

				}
			}
			this.friendBusinessChats = list

		},

		/**
		 * 企业聊天列表
		 */
		resetCompanyChats(companyId) {
			const companyStore = useCompanyStore();
			const companyIds = companyStore.companyList.map((e) => e.id);
			this.companyChats = this.curChats.filter(
				(chat) =>
				// chat.type == this.chatType.GROUP &&
				chat.companyId &&
				chat.companyId == companyId &&
				!chat.originalData.dissolve
			);
			return this.companyChats
		},
	},
	getters: {
		isLoading: (state) => () => {
			return state.loadingPrivateMsg || state.loadingGroupMsg;
		},
		curChats: (state) => {
			return (state.isLoading() && cacheChats) || state.chats;
		},
		findChatIdx: (state) => (chat) => {
			for (let i in state.curChats) {
				if (
					state.curChats[i].type === chat.type &&
					state.curChats[i].targetId == chat.id
				) {
					return i;
				}
			}
			return null;
			/* let chats = state.curChats;
			for (let idx in chats) {
				if (chats[idx].type == chat.type &&
					chats[idx].targetId === chat.targetId) {
					chat = state.chats[idx];
					return idx;
				}
			} */
		},
		findChat: (state) => (msgInfo) => {
			let chats = state.curChats;
			// 获取对方id或群id
			let type = msgInfo.groupId ? "GROUP" : (msgInfo.sourceType === 1 ? "BUSINESS" : "PRIVATE");
			let targetId = msgInfo.groupId ?
				msgInfo.groupId :
				msgInfo.selfSend ?
				msgInfo.recvId :
				msgInfo.sendId;
			let chat = null;
			for (let idx in chats) {
				if (chats[idx].type == type && chats[idx].targetId === targetId) {
					chat = chats[idx];
					break;
				}
			}
			return chat;
		},
		findChatByFriend: (state) => (fid) => {
			return state.curChats.find(
				(chat) => chat.type == "PRIVATE" && chat.targetId == fid
			);
		},
		businessChatByFriend: (state) => (fid) => {
			return state.curChats.find(
				(chat) => chat.type == "BUSINESS" && chat.targetId == fid
			);
		},
		findChatByGroup: (state) => (gid) => {
			return state.curChats.find(
				(chat) => chat.type == "GROUP" && chat.targetId == gid
			);
		},
		findMessage: (state) => (chat, msgInfo) => {
			if (!chat) {
				return null;
			}
			for (let idx in chat.messages) {
				// 通过id判断
				if (msgInfo.id && chat.messages[idx].id == msgInfo.id) {
					return chat.messages[idx];
				}
				// 正在发送中的消息可能没有id,只有tmpId
				if (
					msgInfo.tmpId &&
					chat.messages[idx].tmpId &&
					chat.messages[idx].tmpId == msgInfo.tmpId
				) {
					return chat.messages[idx];
				}
			}
		},
	},
});